﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Quartz;
using TaskMessage.DataAccess;
namespace TaskMessage.Job
{
    public class TaskMessageSend:IJob
    {
        //使用log4net.dll日志接口实现日志记录
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public void Execute(IJobExecutionContext context)
        {
            sendMail();
        }

        public void sendMail()
        {
            logger.Info("Mail 任务开始运行");

            IData data = (IData)Activator.CreateInstance(TaskMessageJobConfig.Instance.DBNamespace, 
                                                string.Format("{0}.{1}",
                                                TaskMessageJobConfig.Instance.DBNamespace,
                                                TaskMessageJobConfig.Instance.DBClassName)).Unwrap();

            ISendMessage sendmessage;
            string[] classname;
            foreach (var item in data.messageList(100))
            {
                logger.InfoFormat("开始发送 id:{0},to:{1},toid:{2}", item.ID,
                    item.ToName, item.ToID);
                classname = item.MessageSendClass.Split(',');
                sendmessage = (ISendMessage)Activator.CreateInstance(classname[0], 
                    classname[0]+"."+classname[1]).Unwrap();

                if (sendmessage.sendMessage(item))
                {
                    data.updateMessageStatus(item.ID, 2);
                    logger.Info("发送成功");
                }
                else
                {
                    data.updateMessageStatus(item.ID, 3);
                    logger.Info("发送失败");
                }
            }
            if (Convert.ToInt32(TaskMessageJobConfig.Instance.jobsleeptime) >= 0)
            {
                System.Threading.Thread.Sleep(Convert.ToInt32(
                                                         TaskMessageJobConfig.Instance.jobsleeptime));
            }
            logger.Info("Mail 任务运行结束");
        }
    }
}
